package com.qingsong.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.relation.RelationManager;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.qingsong.constant.ML;
import com.qingsong.dto.EpisodeExcelDTO;
import com.qingsong.dto.EpisodeInsertDTO;
import com.qingsong.dto.EpisodePageDTO;
import com.qingsong.dto.EpisodeUpdateDTO;
import com.qingsong.entity.Category;
import com.qingsong.entity.Course;
import com.qingsong.entity.Episode;
import com.qingsong.entity.Season;
import com.qingsong.exception.ServiceException;
import com.qingsong.mapper.CommentMapper;
import com.qingsong.mapper.EpisodeMapper;
import com.qingsong.mapper.ReportMapper;
import com.qingsong.service.EpisodeService;
import com.qingsong.util.MinioUtil;
import com.qingsong.vo.EpisodeSimpleListVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mybatisflex.core.paginate.Page;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static com.qingsong.entity.table.CommentTableDef.COMMENT;
import static com.qingsong.entity.table.EpisodeTableDef.EPISODE;
import static com.qingsong.entity.table.ReportTableDef.REPORT;

/**
 * 集次表 服务层实现。
 *
 * @author qingsong
 * @since 2024-12-22
 */
@Service
@CacheConfig(cacheNames = "episode")
public class EpisodeServiceImpl extends ServiceImpl<EpisodeMapper, Episode>  implements EpisodeService{

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private ReportMapper reportMapper;

    @CacheEvict(allEntries = true)
    @Override
    public boolean insert(EpisodeInsertDTO dto) {
        // 标题查重
        if (QueryChain.of(mapper)
                .where(EPISODE.TITLE.eq(dto.getTitle()))
                .exists()) {
            throw new ServiceException("集次标题已存在");
        }
        // 组装 entity 实体类
        Episode episode = BeanUtil.copyProperties(dto, Episode.class);
        episode.setVideo(ML.Episode.DEFAULT_VIDEO);
        episode.setCover(ML.Episode.DEFAULT_VIDEO_COVER);
        episode.setCreated(LocalDateTime.now());
        episode.setUpdated(LocalDateTime.now());
        return mapper.insert(episode) > 0;
    }

    @Cacheable(key = "#p0", condition = "#p0 != null", unless = "#result == null")
    @Override
    public Episode select(Long id) {
        RelationManager.addQueryRelations("season");
        return mapper.selectOneWithRelationsById(id);
    }

    @Cacheable(key = "#root.methodName", unless = "#result == null")
    @Override
    public List<EpisodeSimpleListVO> simpleList() {
        return QueryChain.of(mapper)
                .orderBy(EPISODE.IDX.asc(), EPISODE.ID.desc())
                .withRelations()
                .listAs(EpisodeSimpleListVO.class);
    }

    @Override
    @Cacheable(key = "#root.methodName + ':' + #p0.toString()", unless = "#result == null")
    public Page<Episode> page(EpisodePageDTO dto) {
        RelationManager.addQueryRelations("season");
        QueryChain<Episode> queryChain = QueryChain.of(mapper)
                .orderBy(EPISODE.IDX.asc(), EPISODE.ID.desc());
        // title 条件
        String title = dto.getTitle();
        if (ObjectUtil.isNotNull(title)) {
            queryChain.where(EPISODE.TITLE.like(title));
        }
        // seasonId 条件
        Long seasonId = dto.getFkSeasonId();
        if (ObjectUtil.isNotNull(seasonId)) {
            queryChain.where(EPISODE.FK_SEASON_ID.eq(seasonId));
        }
        return queryChain.withRelations()
                .page(new Page<>(dto.getPageNum(), dto.getPageSize()));
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean update(EpisodeUpdateDTO dto) {
        // 标题查重
        if (QueryChain.of(mapper)
                .where(EPISODE.TITLE.eq(dto.getTitle()))
                .and(EPISODE.ID.ne(dto.getId()))
                .exists()) {
            throw new ServiceException("集次标题已存在");
        }
        // 组装 entity 实体类
        Episode episode = BeanUtil.copyProperties(dto, Episode.class);
        episode.setUpdated(LocalDateTime.now());
        return UpdateChain.of(episode)
                .where(EPISODE.ID.eq(episode.getId()))
                .update();
    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean delete(Long id) {

        // 查询该集次关联的全部评论ID
        // select id from comment where fk_episode_id = ?
        List<Long> commentIds = QueryChain.of(commentMapper)
                .select(COMMENT.ID)
                .where(COMMENT.FK_EPISODE_ID.eq(id))
                .listAs(Long.class);

        // 查询该集次关联的全部评论的子评论ID
        // select id from comment where pid in (commentIds)
        List<Long> subCommentIds = QueryChain.of(commentMapper)
                .select(COMMENT.ID)
                .where(COMMENT.PID.in(commentIds))
                .listAs(Long.class);

        // 组合全部待删除的评论ID
        commentIds.addAll(subCommentIds);

        // 删除该集次的全部评论
        // delete from comment where id in (commentIds)
        UpdateChain.of(commentMapper)
                .where(COMMENT.ID.in(commentIds))
                .remove();

        // 删除该集次的全部举报
        // delete from report where fk_episode_id =?
        UpdateChain.of(reportMapper)
                .where(REPORT.FK_EPISODE_ID.eq(id))
                .remove();

        // 删除集次
        // delete from episode where id =?
        return mapper.deleteById(id) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean deleteBatch(List<Long> ids) {
        // 删除该集次的全部评论
        UpdateChain.of(commentMapper)
                .where(COMMENT.FK_EPISODE_ID.in(ids))
                .remove();

        // 删除该集次的全部举报
        UpdateChain.of(reportMapper)
                .where(REPORT.FK_EPISODE_ID.in(ids))
                .remove();

        // 删除集次
        return mapper.deleteBatchByIds(ids) > 0;
    }

    @CacheEvict(allEntries = true)
    @Override
    public String uploadVideo(MultipartFile videoCoverFile, Long id) {
        // 按主键查询用户记录
        Episode episode = mapper.selectOneById(id);
        if (ObjectUtil.isNull(episode)) {
            throw new ServiceException("用户不存在");
        }
        // 备份旧头像
        String oldAvatar = episode.getVideo();
        // 重新生成文件名
        String filename = MinioUtil.randomFilename(videoCoverFile);
        // 根据用户主键修改用户头像
        episode.setVideo(filename);
        if (mapper.update(episode) <= 0) {
            throw new ServiceException("头像更新失败：DB操作异常");
        }
        try {
            // 从MinIO中删除旧头像：默认头像不删除
            if (!ML.Episode.DEFAULT_VIDEO.contains(oldAvatar)) {
                MinioUtil.delete(oldAvatar, ML.MinIO.EPISODE_VIDEO_DIR, ML.MinIO.BUCKET_NAME);
            }
            // 向MinIO中上传新头像
            MinioUtil.upload(videoCoverFile, filename, ML.MinIO.EPISODE_VIDEO_DIR, ML.MinIO.BUCKET_NAME);
        } catch (Exception e) {
            throw new ServiceException("头像更新失败：MinIO操作异常");
        }
        // 返回文件名
        return filename;
    }

    @CacheEvict(allEntries = true)
    @Override
    public String uploadVideoCover(MultipartFile videoFile, Long id) {
        // 按主键查询用户记录
        Episode episode = mapper.selectOneById(id);
        if (ObjectUtil.isNull(episode)) {
            throw new ServiceException("用户不存在");
        }
        // 备份旧头像
        String oldAvatar = episode.getCover();
        // 重新生成文件名
        String filename = MinioUtil.randomFilename(videoFile);
        // 根据用户主键修改用户头像
        episode.setCover(filename);
        if (mapper.update(episode) <= 0) {
            throw new ServiceException("头像更新失败：DB操作异常");
        }
        try {
            // 从MinIO中删除旧头像：默认头像不删除
            if (!ML.Episode.DEFAULT_VIDEO_COVER.contains(oldAvatar)) {
                MinioUtil.delete(oldAvatar, ML.MinIO.EPISODE_VIDEO_COVER_DIR, ML.MinIO.BUCKET_NAME);
            }
            // 向MinIO中上传新头像
            MinioUtil.upload(videoFile, filename, ML.MinIO.EPISODE_VIDEO_COVER_DIR, ML.MinIO.BUCKET_NAME);
        } catch (Exception e) {
            throw new ServiceException("头像更新失败：MinIO操作异常");
        }
        // 返回文件名
        return filename;
    }

    @Override
    public List<EpisodeExcelDTO> excel() {
        // 加1层递归深度: episode -> season -> course -> category
        RelationManager.setMaxDepth(4);
        // 查询全部集次记录
        List<Episode> episodes = mapper.selectAllWithRelations();
        // List<Episode> -> List<EpisodeExcelDTO>
        List<EpisodeExcelDTO> result = new ArrayList<>();
        episodes.forEach(episode -> {
            // 赋值 Episode 相关信息
            EpisodeExcelDTO episodeExcelDTO = BeanUtil.copyProperties(episode, EpisodeExcelDTO.class);
            // 赋值 Season 相关信息
            Season season = episode.getSeason();
            episodeExcelDTO.setSeasonTitle(season.getTitle());
            episodeExcelDTO.setSeasonInfo(season.getInfo());
            // 赋值 Course 相关信息
            Course course = season.getCourse();
            episodeExcelDTO.setCourseTitle(course.getTitle());
            episodeExcelDTO.setCourseInfo(course.getInfo());
            episodeExcelDTO.setPrice(course.getPrice());
            episodeExcelDTO.setAuthor(course.getAuthor());
            // 赋值 Category 相关信息
            Category category = course.getCategory();
            episodeExcelDTO.setCategoryTitle(category.getTitle());
            result.add(episodeExcelDTO);
        });
        return result;
    }

}
